import { Tabbar, TabbarItem } from 'react-vant'
import { switchTab, getCurrentPages } from '@tarojs/taro'
import './index.css'

const TabBar = () => {
  const pages = getCurrentPages()
  const currentRoute = pages[pages.length - 1]?.route || ''
  const current = currentRoute.endsWith('message/index') ? 'message' :
                currentRoute.endsWith('function/index') ? 'function' :
                currentRoute.endsWith('mine/index') ? 'mine' : 'home'

  const tabs = [
    { 
      id: 'home',
      title: '首页',
      icon: (
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" fill="currentColor"/>
        </svg>
      )
    },
    { 
      id: 'message',
      title: '消息',
      icon: (
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z" fill="currentColor"/>
        </svg>
      )
    },
    { 
      id: 'function',
      title: '功能',
      icon: (
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z" fill="currentColor"/>
        </svg>
      )
    },
    { 
      id: 'mine',
      title: '我的',
      icon: (
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z" fill="currentColor"/>
        </svg>
      )
    }
  ]

  const handleTabClick = (tabId: string) => {
    if (tabId === current) return
    
    let url = ''
    switch(tabId) {
      case 'home':
        url = '/merchant/pages/index/index'
        break
      case 'message':
        url = '/merchant/pages/message/index'
        break
      case 'function':
        url = '/merchant/pages/function/index'
        break
      case 'mine':
        url = '/merchant/pages/mine/index'
        break
    }
    switchTab({ url })
  }

  return (
    <Tabbar 
      fixed 
      safeAreaInsetBottom
      value={current}
      onChange={(active) => handleTabClick(active as string)}
    >
      {tabs.map(tab => (
        <TabbarItem
          key={tab.id}
          name={tab.id}
          icon={tab.icon}
        >
          {tab.title}
        </TabbarItem>
      ))}
    </Tabbar>
  )
}

export default TabBar
